package org.example.software.controller;

import org.example.software.entity.Admin;
import org.example.software.exception.MyException;
import org.example.software.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    //管理员注册
    @PostMapping("/register")
    public ResponseEntity<?> registerAdmin(@RequestBody Admin admin) {
        try {
            boolean success = adminService.register(admin);
            if (success) {
                return ResponseEntity.ok("管理员注册成功");
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("管理员注册失败");
            }
        } catch (MyException e) {
            // 捕获 MyException，自定义返回状态码和消息
            return ResponseEntity.status(e.getCode()).body(e.getMessage());
        }
        catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误");
        }
    }

    // 管理员登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Admin admin) {
        try {
            String token = adminService.login(admin);
            if (token != null) {
                return ResponseEntity.ok(token);
            }
            else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("管理员登录失败");
            }
        } catch (MyException e) {
            // 捕获 MyException，自定义返回状态码和消息
            return ResponseEntity.status(e.getCode()).body(e.getMessage());
        }
        catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误");
        }
    }


}
